package com.lagou.server;

import com.lagou.invoke.RpcRequest;
import com.lagou.serializer.JSONSerializer;
import com.lagou.serializer.RpcDecoder;
import com.lagou.server.handler.NettyInvocationHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/26
 */
@SpringBootApplication
public class ServerBootstrap implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(ServerBootstrap.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        io.netty.bootstrap.ServerBootstrap bootstrap = new io.netty.bootstrap.ServerBootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new NettyInvocationHandler());
                    }
                });
        bootstrap.bind("localhost", 8081);
    }
}
